package com.rchat.pocmini.service;

import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.Nullable;

import com.itsdf07.alog.ALog;
import com.rchat.pocmini.bean2eventbus.EventBusRemoteBean;
import com.rchat.remote.aidl.IRchatClinetAidl;
import com.rchat.remote.aidl.IRchatRemoteAidl;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * Rchat客户端Service
 * Created by itsdf07 on 2017/8/17.
 */

public class RchatClientService extends Service {
    private final String TAG = this.getClass().getSimpleName();

    /**
     * Client的包名
     */
    private final String RCHAT_PACKAGE = "com.rchat.pocmini";
    /**
     * 远程apk的包名
     */
    private final String REMOTE_PACKAGE = "com.rchat.remote";
    /**
     * 远程apk的服务
     */
    private final String REMOTE_PACKAGE_SERVICE = REMOTE_PACKAGE + ".RchatRemoteService";
    /**
     * 远程apk的启动页面
     */
    private final String REMOTE_START_ACTIVITY = REMOTE_PACKAGE + ".MainActivity";
    /**
     * 远程apk的启动页面
     */
    private final String REMOTE_START_ACTIVITY_BY_ACTION = "com.rchat.remote.intent.action.third.MAIN";

    /**
     * 是否绑定远程服务
     */
    private boolean isBindRemote = false;

    private IRchatRemoteAidl mRchatRemoteAidl;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        ALog.dTag(TAG, "action = " + intent.getAction());
        return remoteBinder;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        boolean status = super.onUnbind(intent);
        ALog.dTag(TAG, "status = %s,action = %s" + status + ":" + intent.getAction());
        return status;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        ALog.dTag(TAG, "onCreate...");
        EventBus.getDefault().register(this);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        int status = super.onStartCommand(intent, flags, startId);
        ALog.dTag(TAG, "status = %s" + status);
        return status;
    }

    @Override
    public void onDestroy() {
        ALog.dTag(TAG, "onDestroy ...");
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventBusDispatchRemote(EventBusRemoteBean bean) {
        if (bean == null || !bean.isTarget(this.getClass())) {
            return;
        }
        ALog.dTag(TAG, "currentEvent = %s", bean.getCurrentEvent());
        switch (bean.getCurrentEvent()) {
            case EventBusRemoteBean.EVENT_STARTREMOTE:
                start2Action(REMOTE_START_ACTIVITY_BY_ACTION);
                break;
            case EventBusRemoteBean.EVENT_BINDREMOTE:
                isBindRemote = true;
                bindRemoteService();
                break;
            case EventBusRemoteBean.EVENT_UNBINDREMOTE:
                isBindRemote = false;
                if (null != mRchatRemoteAidl) {
                    try {
                        mRchatRemoteAidl.setMonitor(isBindRemote);
                        unBindRemoteService();
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }

//            stopSelf();
                break;
            default:
                break;
        }
    }

    /**
     * 通过直接设置包名、类名启动另外一个apk的界面Activity，
     * 其中该Activity在对应apk中的manifest不需要额外其他的设置
     */
    private void start2ClassName(String clazz) {
        ALog.dTag(TAG, "...");
        //方式一
//        Intent intent = new Intent();
//        intent.setClassName(REMOTE_PACKAGE, REMOTE_START_ACTIVITY);
//        startActivity(intent);
        //方式二
        Intent intent = new Intent();
        ComponentName cn = new ComponentName(REMOTE_PACKAGE, clazz);
        intent.setComponent(cn);
        try {
            startActivity(intent);
        } catch (Exception e) {
            ALog.eTag(TAG, "睿洽插件安装：%s", e.toString());
        }
    }

    /**
     * "com.rchat.remote.intent.action.third.MAIN"
     * 通过action启动另外一个apk的界面Activity，
     * 其中该Activity在对应apk中的manifest需要额外其他的设置：
     * <intent-filter>
     * <action android:name="com.rchat.remote.intent.action.third.MAIN" />
     * <!--必须加上这个，否则下面无法直接使用自定的action-->
     * <category android:name="android.intent.category.DEFAULT" />
     * </intent-filter>
     */
    private void start2Action(String action) {
        ALog.dTag(TAG, "action = %s", action);
        Intent intent = new Intent();
        intent.setAction(action);
        /**
         * Caused by: android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
         *Context中有一个startActivity方法，Activity继承自Context，重载了startActivity方法。
         * 如果使用Activity的startActivity方法，不会有任何限制，而如果使用Context的startActivity方法的话，就需要开启一个新的task，
         * 遇到上面那个异常的，都是因为使用了Context的startActivity方法。解决办法是，加一个flag。
         * intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
         * 备注：华为P9和Nexus 5X没加这句话也是没问题，其他好像都有问题
         */
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setPackage(REMOTE_PACKAGE);
        Bundle bundle = new Bundle();
        bundle.putString("arg1_packagge", RCHAT_PACKAGE);
        intent.putExtras(bundle);
        try {
            startActivity(intent);
        } catch (Exception e) {
            ALog.eTag(TAG, "睿洽插件未安装：%s", e.toString());
        }
    }

    /**
     * 绑定远程服务
     */
    private void bindRemoteService() {
        ALog.dTag(TAG, "...");
        Intent intent = new Intent();
        ComponentName cn = new ComponentName(REMOTE_PACKAGE, REMOTE_PACKAGE_SERVICE);
        intent.setComponent(cn);
        bindService(intent, remoteConnection, BIND_AUTO_CREATE);
    }

    /**
     * 解绑远程服务
     */
    private void unBindRemoteService() {
        unbindService(remoteConnection);
    }

    IRchatClinetAidl.Stub remoteBinder = new IRchatClinetAidl.Stub() {
        @Override
        public String connectRemote(String msg) throws RemoteException {
            ALog.dTag(TAG, "msg = %s", msg);
            bindRemoteService();
            return msg;
        }

        @Override
        public boolean bindRemoteService() throws RemoteException {
            EventBusRemoteBean bean = new EventBusRemoteBean();
            bean.setCurrentEvent(EventBusRemoteBean.EVENT_BINDREMOTE);
            bean.setTarget(RchatClientService.class, RchatClientService.class, "onEventBusDispatchRemote");
            onEventBusDispatchRemote(bean);
            return true;
        }

        @Override
        public String testInfo(String msg) throws RemoteException {
            return null;
        }
    };


    /**
     * 远程服务的连接
     */
    ServiceConnection remoteConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            ALog.dTag(TAG, "name = %s", name.toString());
            mRchatRemoteAidl = IRchatRemoteAidl.Stub.asInterface(service);
            try {
                if (null != mRchatRemoteAidl) {
                    mRchatRemoteAidl.connectRemote("与客户端服务连接成功");

//                    if (isBindRemote) {
//                        mRchatRemoteAidl.setMonitor(true);
//                    }
                } else {
                    ALog.eTag(TAG, "mRchatRemoteServiceAidl = null");
                }
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            ALog.dTag(TAG, "isBindRemote = %s，ComponentName = %s", isBindRemote, name.toString());
            unBindRemoteService();
            start2Action(REMOTE_START_ACTIVITY_BY_ACTION);
        }
    };
}
